﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.DependencyInjection;

namespace Xms.Abp.Storage.DependencyInjection;

internal static class AbpDbContextOptionsExtensions
{
    public static List<Action<AbpDbContextConfigurationContext>> GetDefaultPreConfigureActions(this AbpDbContextOptions options)
        => GetInternalProperty<List<Action<AbpDbContextConfigurationContext>>>(options);
    public static Action<AbpDbContextConfigurationContext> GetDefaultConfigureAction(this AbpDbContextOptions options)
        => GetInternalProperty<Action<AbpDbContextConfigurationContext>>(options);
    public static Dictionary<Type, List<object>> GetPreConfigureActions(this AbpDbContextOptions options)
        => GetInternalProperty<Dictionary<Type, List<object>>>(options);
    public static Dictionary<Type, object> GetConfigureActions(this AbpDbContextOptions options)
        => GetInternalProperty<Dictionary<Type, object>>(options);
    public static Dictionary<Type, Type> GetDbContextReplacements(this AbpDbContextOptions options)
        => GetInternalProperty<Dictionary<Type, Type>>(options);

    private static T GetInternalProperty<T>(AbpDbContextOptions options, [CallerMemberName]string methodName = null)
    {
        var propertyName = methodName.RemovePreFix("Get");
        var type = options.GetType();
        var property = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance).First(r => r.Name == propertyName);
        return (T)property.GetValue(options);
    }
}
